package com.hbu.housingbrokerug.activities;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.fedorvlasov.lazylist.LazyAdapter;
import com.hbu.housingbrokeruganda.Parser.JSONParser;
import com.hub.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

/**
 * @author Lubwama Samuel(lubwamasamuel3[at]gmail[dot]com)
 */
public class SearchByLocation extends SearchBaseActivity{
	private ProgressDialog pDialog;
	ListView list;
    LazyAdapter adapter;
    int sizeOfArray=0;
    EditText city, district, town, village;
    Button search_button;
    String result="";
    int arraysize;
    JSONParser jParser =new JSONParser();
    TextView messageSearch;  
parserFromUrl parser=new parserFromUrl();
	
public String[][] IMAGES;

DisplayImageOptions options=parser.getOptions();
public String ipOrDomain=parser.getIpOrDomain();

public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.search_location);
	search_button=(Button)findViewById(R.id.search_location_ok);
	search_button.setOnClickListener(new OnClickListener() {	
		@Override
		public void onClick(View v) {
			district=(EditText)findViewById(R.id.district);
			city=(EditText)findViewById(R.id.city);
			town=(EditText)findViewById(R.id.town);
			village=(EditText)findViewById(R.id.village);
			list=(ListView)findViewById(R.id.listViewAllunits_search_location);
			list.clearChoices();
			// TODO Auto-generated method stub
			IMAGES=new String[][]{};
			new  getAllHousingUnitInformation(district.getText().toString(), city.getText().toString(),town.getText().toString(),village.getText().toString()).execute();
		}
	});
}
@Override
public void onBackPressed() {
	Bundle bundle=getIntent().getExtras();
	Intent intentSearch = new Intent(this,  Search.class);
	intentSearch.putExtra("CATEGORY_ID", bundle.getString("CATEGORY_ID"));
	intentSearch.putExtra("CATEGORY_NANE", bundle.getString("CATEGORY_NAME"));
	startActivity(intentSearch);
	finish();
 return;
}
	
public void onDestroy(){
	try{
        list.setAdapter(null);
	}catch(Exception e){
		
	}
		super.onDestroy();
	    }	
	//getting one unit 
	private void startingSingleUnit(int position) {
		// getting values from selected ListItem	
		// Starting new intent    
		Intent intent = new Intent(getApplicationContext(),SingleUnit.class);
		// sending pid to next activity
		intent.putExtra("UNIT_ID",IMAGES[position][0]);
		intent.putExtra("UNIT_DISTRICT",IMAGES[position][2]);
		intent.putExtra("UNIT_CITY",IMAGES[position][3]);
		intent.putExtra("UNIT_TOWN",IMAGES[position][4]);
		intent.putExtra("UNIT_VILLAGE",IMAGES[position][5]);
		intent.putExtra("UNIT_LATITUDE",IMAGES[position][6]);
		intent.putExtra("UNIT_LONGITUDE",IMAGES[position][7]);
		intent.putExtra("UNIT_CATEGORY",IMAGES[position][8]);
		intent.putExtra("UNIT_COST",IMAGES[position][9]);
		intent.putExtra("LANDLORD_FIRSTNAME",IMAGES[position][10]);
		intent.putExtra("LANDLORD_LASTNAME",IMAGES[position][11]);
		intent.putExtra("CONTACTS",IMAGES[position][12]);		
		// starting new activity and expecting some response back
		startActivityForResult(intent, 100);
		
	}		
public class getAllHousingUnitInformation extends AsyncTask<String, String, String> {

	public getAllHousingUnitInformation(String string, String string2, String string3, String string4) {
	}

		@Override
		protected String doInBackground(String... params) {
			final String TAG_SUCCESS = "success";
			final String HOUSING_UNIT = "housing_units";
		try{
			district=(EditText)findViewById(R.id.district);
			city=(EditText)findViewById(R.id.city);
			town=(EditText)findViewById(R.id.town);
			village=(EditText)findViewById(R.id.village);
			Log.d("EDITOR VALUE", district.getText().toString());	
				JSONObject json2=jParser.makeHttpRequest((parser.getIpOrDomain()+parser.getQueryFile()).toString(),"GET", parser.getParametersSearchByLocation((district.getText().toString()),(city.getText().toString()),(town.getText().toString()), (village.getText().toString())));			
					int	 success = json2.getInt(TAG_SUCCESS);				
					Log.d("SUCCESS TAG", String.valueOf(json2.getInt(TAG_SUCCESS)));
					if (success == 1) {
						 JSONArray jArray=json2.getJSONArray(HOUSING_UNIT);		    			
						 IMAGES=new String[jArray.length()][13];
						 for(int i=0;i<jArray.length();i++){	
							JSONObject json1=jArray.getJSONObject(i);
					/*1*/	IMAGES[i][0]=json1.getString("unit_id");
					/*2*/	IMAGES[i][1]=parser.getIpOrDomain()+json1.getString("urls_image");
					/*3*/	IMAGES[i][2]=json1.getString("district");
					/*4*/	IMAGES[i][3]=json1.getString("city");
					/*5*/	IMAGES[i][4]=json1.getString("town");
					/*6*/	IMAGES[i][5]=json1.getString("village");
					/*7*/	IMAGES[i][6]=json1.getString("latitude");
					/*8*/	IMAGES[i][7]=json1.getString("longitude");
					/*9*/	IMAGES[i][8]=json1.getString("unit_category");
					/*10*/	IMAGES[i][9]=json1.getString("cost");
					/*11*/	IMAGES[i][10]=json1.getString("last_name");
					/*12*/	IMAGES[i][11]=json1.getString("first_name");
					/*13*/	IMAGES[i][12]=json1.getString("phone");
					 }			 
					}
				else{
							IMAGES=new String[1][1];
							IMAGES[0][0]="No Results";			
					}
					
		}catch(Exception e){
						Log.e("FAILED TO PASS DATA", e.toString());
		}							
			return null;
		}
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */	
					Log.d("DATA TRIAL", String.valueOf(IMAGES.length));
				if(IMAGES[0][0]!="No Results"){
					 messageSearch=(TextView)findViewById(R.id.search_result_message);
					 messageSearch.setText(IMAGES.length+" Matching Results");
		    	    list=(ListView)findViewById(R.id.listViewAllunits_search_location);
			        adapter=new LazyAdapter(SearchByLocation.this, IMAGES,ipOrDomain);
			        list.setAdapter(adapter);
			        list.setItemsCanFocus(true);
			        list.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
							startingSingleUnit(position);
						}
					});		        			        
				}
				else{	
					district=(EditText)findViewById(R.id.district);
					city=(EditText)findViewById(R.id.city);
					town=(EditText)findViewById(R.id.town);
					village=(EditText)findViewById(R.id.village);
				    messageSearch=(TextView)findViewById(R.id.search_result_message);
				    messageSearch.setText("No Housing Units For price range\n " +district.getText().toString()+ " - "+city.getText().toString());
					Intent intent = new Intent(SearchByLocation.this,SearchByLocation.class);
				    intent.putExtra("MESSAGE", "No Results For price range " +district.getText().toString()+ " - "+city.getText().toString());
				    list=(ListView)findViewById(R.id.listViewAllunits_search_location);
				    list.setAdapter(null);
				}
				}
			});
		}	
	}	
@Override
public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(R.menu.searchbylocation, menu);
	return true;
}
}